  function [sigma,d1,v1]=drawsigcd(erdata,v0,s0,Qb,nk,np); 
% function [sigma,d1,v1]=drawsigcd(erdata,v0,s0,Qb,nk,np); 
% 
% Draws from the posterior of a Variance 
% sigma is distributed as in IG(v0,s0)
% And the prior for B is conditional on sigma 
% i.e. requires using drawncd.m 
%
% Formulas follow Chib JE (1993)
%
% v0    degrees of freedom   
% s0    scale parameter 
% Qb    distance between the B drawn and the prior 
% nk    dimension of B 
% np     number of lags in the AR terms 
%       if not provided or empty will be assumed equal to zero 
% 
% Posterior is: 
% sigma^2 ~ IG ([T+K-P + v0 , s0+erdata'erdata + Qb )
%
% sigma     sampled variance 
% v1        posterior degrees of freedom 
% d1        posterior scale parameter 
%
% Using integer values for v0 results in faster sampling 
% Note: previous codes named d0 the degrees of freedom 
%       checked here for consistency 
% 
%
% 2/03/04
if ( nargin < 6 | isempty(np) == 1 )
    np=0;  
end 
    
v1= v0 + length(erdata) - np + nk; 
s1=( (erdata')*erdata ) + s0 + Qb; 

if ( floor(v1) - v1 ) == 0 
    nor=randn(v1,1); 
    chi=nor'*nor; 
    sigma=s1/chi; 
else 
    sigma=1./gamrnd(v1/2,2/s1,1,1) 
end 